package com.liush.system.config;

import com.liush.system.filter.TokenAuthenticationFilter;
import com.liush.system.filter.TokenLoginFilter;
import com.liush.system.service.LoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//配置类 (代替配置文件)
@SpringBootConfiguration
@EnableWebSecurity  //启用springsecurity 默认配置
@EnableGlobalMethodSecurity(prePostEnabled = true)//控制器方法权限判断开启
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginLogService loginLogService;

    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); //禁用csrf
        http.cors(); //支持跨域
        // 登录地址访问直接放行,服务器其它资源必须登陆成功才能访问
        http.authorizeRequests()
                .antMatchers("/admin/system/index/login", "/admin/system/index/info", "/admin/system/index/logout")
                .permitAll().anyRequest().authenticated();
        // 注册过滤器
        http.addFilter(new TokenLoginFilter(authenticationManager(), redisTemplate, loginLogService));
        http.addFilterBefore(new TokenAuthenticationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class);
        // 禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    /**
     * 配置哪些请求不拦截
     * 排除swagger相关请求
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/favicon.ico", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html");
    }
}
